package com.flashcash.kotlin.fragment.certfication

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat.startActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.widget.ImageButton
import android.widget.ProgressBar
import android.widget.TextView
import com.flashcash.kotlin.activity.InfoFillActivity
import com.flashcash.kotlin.data.CertBean
import com.flashcash.kotlin.face.DeltaHolder
import com.flashcash.kotlin.trace.TraceManager
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils
import com.flashcash.solu.R
import com.flashcash.solu.bean.LatestLoanAppBean
import com.flashcash.solu.bean.ProgressBean
import com.flashcash.solu.common.FieldParams
import com.flashcash.solu.common.FieldParamsInt
import com.flashcash.solu.common.TokenManager
import com.flashcash.solu.view.IntroduceActivity
import com.flashcash.solu.view.MainActivity
import com.flashcash.solu.view.camera.FaceDetectorFragment
import com.flashcash.solu.view.camera.FaceDetectorPreImpl
import com.flashcash.solu.view.camera.FaceDetectorView
import com.flashcash.solu.view.certification.*
import com.flashcash.solu.view.fragment.presenter.CertifiFraProPresenter
import com.flashcash.solu.widget.xleotoast.XLeoToast
import com.x.leo.apphelper.data.cache.CacheDataManage
import com.x.leo.timelineview.TimeLineView
import org.jetbrains.anko.backgroundDrawable
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onClick
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

/**
 * Created by XLEO on 2018/1/18.
 */
class CertifyFragment : FaceDetectorFragment<CertifiFraProPresenter>(), CertifiFraView {
    private var isFaceDetecting = false
    override fun submitButtonStateUpdate(active: Boolean) {
        isFaceDetecting = !active
        changeSubmitButtonState()
    }

    companion object {
        private val FACE_DETECT_REQUEST_CODE = 0x010F
    }

    private var isFullFilled: Boolean = false
    private var gotoFacebooked: Boolean = false
    private var firstLoad: Boolean = true

    private fun changeSubmitButtonState() {
        val result = (!isFaceDetecting) && isFullFilled
        /*if (Looper.myLooper() == Looper.getMainLooper()) {
            submitButton.isSelected = !result
            submitButton.isClickable = result
        } else {
            activity?.runOnUiThread {
                submitButton.isSelected = !result
                submitButton.isClickable = result
            }
        }*/
    }

    override fun doPreBuildHeader(): Boolean {
        return false
    }

    /*override fun initHeader(view: TextView?): Boolean {
        view?.textResource = R.string.textview_my_loan
        return false
    }*/

    override fun onSuccess(arrayList: ArrayList<CertBean>) {
        certDatas.clear()
        certDatas.addAll(arrayList)
        updateView()
    }

    override fun onError(exception: Exception) {
        resetCertItem()
        if (isVisible) {
            AlertDialog.Builder(context)
                    .setTitle(R.string.tips_title)
                    .setMessage(R.string.error_occured)
                    .setPositiveButton(R.string.retry, { dialog, _ ->
                        dialog.dismiss()
                        initData()
                    })
                    .show()
        }
    }

    override fun initPresenter(): CertifiFraProPresenter {
        return CertificatyFraPreImpl()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_certficaty
    }

    private lateinit var progressBar: ProgressBar
    private lateinit var progressText: TextView
    private lateinit var recycleview: RecyclerView
    //    private lateinit var submitButton: Button
    private var animationEnd: Boolean = false

    override fun initView(view: View?, savedInstanceState: Bundle?) {
        progressBar = view!!.find(R.id.id_progressbar_certification)
        view.find<ImageButton>(R.id.id_imagebutton_back).onClick {
            if ((activity as CertifyActivity).isFromSplash) {
                startActivity(Intent(activity, IntroduceActivity::class.java))
            }
            activity!!.finish()
        }
        progressText = view.find(R.id.id_textview_rating)
        recycleview = view.find(R.id.recyclerView)
//        submitButton = view.find(R.id.id_button_certification_submit)

        /*submitButton.onClick {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_APPLY_SUBMIT, null)
            startActivityForResult(Intent(getContext(), FacebookAccountActivity::class.java), 10086)
        }*/

        recycleview.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        recycleview.adapter = CerticatyAdapter(certDatas)
        recycleview.scheduleLayoutAnimation()
        recycleview.layoutAnimationListener = object : Animation.AnimationListener {
            override fun onAnimationRepeat(animation: Animation?) {
            }

            override fun onAnimationStart(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                animationEnd = true
                recycleview.adapter.notifyDataSetChanged()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 10086 && resultCode == 10010) {//从facebook页面接收结果
            TraceManager.qualifyPermissions(mActivity, Runnable {
                showFaceDetectorDialog()
            })
        }

        if (requestCode == FACE_DETECT_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                showLoading()
                submitButtonStateUpdate(false)
                mPresenter.uploadFaces(DeltaHolder.instance.delta) // 上传大礼包
            } else {
                when (data) {
                    null -> XLeoToast.showMessage(R.string.detect_live_face_fail)
                    else -> XLeoToast.showMessage(data.extras.getString(FieldParams.LivenessExtras.FAILED_MSG))
                }
                XLeoToast.showMessage(R.string.detect_live_face_fail)
                activity!!.finish()
            }
        }
    }

    private val certDatas: ArrayList<CertBean> by lazy {
        val temp = ArrayList<CertBean>()
        //默认数据
        temp.add(CertBean(true))
        temp.add(CertBean(true))
        temp.add(CertBean(true))
        temp.add(CertBean(true))
        temp
    }

    //todo 从这里得知是否显示认证页面的提交按钮
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            /*if (MainActivity.isSubmitVisible) {
                submitButton.visibility = View.VISIBLE
            } else {
                submitButton.visibility = View.GONE
            }*/
            isFaceDetecting = false
            mPresenter.downloadState()
        }
    }

    override fun onResume() {
        super.onResume()
        if (isVisible) {
            /*if (MainActivity.isSubmitVisible) {
                submitButton.visibility = View.VISIBLE
            } else {
                submitButton.visibility = View.INVISIBLE
            }*/
//            mPresenter.downloadState()
        }
        mPresenter.downloadState()
    }

    override fun resetCertItem() {
        certDatas.forEach {
            it.isComplete = false
        }
        updateView()
    }

    @SuppressLint("SetTextI18n")
    private fun updateView() {
        if (animationEnd) {
            recycleview.adapter.notifyDataSetChanged()
        }
        var percent = 0
        certDatas.forEach {
            if (it.isComplete) {
                percent += 25
            }
        }
        isFullFilled = percent == 100
        if (isFullFilled && (activity as CertifyActivity).isGotoLoaning && !gotoFacebooked) {//跳转到Facebook页面
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_APPLY_SUBMIT, null)
            startActivityForResult(Intent(getContext(), FacebookAccountActivity::class.java), 10086)
            gotoFacebooked = true
        }

        if (MainActivity.isSubmitVisible) {
            changeSubmitButtonState()

        }
        progressText.text = "" + percent + "%"
        progressBar.progress = percent
    }

    override fun initData() {
    }
}

class CerticatyAdapter(var certDatas: ArrayList<CertBean>) : RecyclerView.Adapter<CertViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CertViewHolder {
        val inflate = LayoutInflater.from(parent.context).inflate(R.layout.item_cert, parent, false)
        return CertViewHolder(inflate)
    }

    override fun onBindViewHolder(holder: CertViewHolder, position: Int) {
        holder.injectData(position, certDatas[position], if (position == 0) null else certDatas[position - 1])
    }

    override fun getItemCount(): Int {
        return certDatas.size
    }

}

class CertViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    @SuppressLint("SetTextI18n")
    fun injectData(position: Int, curr: CertBean, last: CertBean?) {
        val level: Int
        val state = when {
            curr.isComplete -> {
                level = 2
                TimeLineView.COMPLETE
            }
            position == 0 -> {
                level = 1
                TimeLineView.ACTIVE
            }
            else -> when (last?.isComplete) {
                true -> {
                    level = 1
                    TimeLineView.ACTIVE
                }
                else -> {
                    level = 0
                    TimeLineView.INACTIVE
                }
            }
        }


        /*itemView.find<LinearLayout>(R.id.panel).apply {
            val resId = when (position) {
                0 -> {
                    R.drawable.cert_status_icon_identify_level
                }
                1 -> {
                    R.drawable.cert_status_icon_personal_level
                }
                2 -> {
                    R.drawable.cert_status_icon_contact_level
                }
                3 -> {
                    R.drawable.cert_status_icon_professional_level
                }
                else -> {
                    R.drawable.cert_status_icon_professional_level
                }
            }
            setBackgroundResource(resId)
        }*/


//        itemView.find<ImageView>(R.id.icon).apply {
//            imageResource = when (position) {
//                0 -> {
//                    R.drawable.cert_status_icon_identify_level
//                }
//                1 -> {
//                    R.drawable.cert_status_icon_personal_level
//                }
//                2 -> {
//                    R.drawable.cert_status_icon_contact_level
//                }
//                3 -> {
//                    R.drawable.cert_status_icon_professional_level
//                }
//                else -> {
//                    R.drawable.cert_status_icon_personal_level
//                }
//            }
//            setImageLevel(level)
//        }

        itemView.find<TextView>(R.id.desc).apply {
            setText(when (position) {
                0 -> {
                    R.string.textview_field_identity_info
                }
                1 -> {
                    R.string.textview_field_personal_info
                }
                2 -> {
                    R.string.textview_field_contract_info
                }
                3 -> {
                    R.string.textview_field_professional_info
                }
                else -> {
                    R.string.textview_field_identity_info
                }
            })
        }
        val tvDesc = itemView.find<TextView>(R.id.desc)
        when (level) {
            0, 1 -> tvDesc.isSelected = false
            2 -> tvDesc.isSelected = true
        }

        /*itemView.find<TextView>(R.id.step).apply {
            text = "STEP " + (position + 1)
            backgroundDrawable?.level = level
        }*/




        itemView.find<TextView>(R.id.check_result).apply {
            visibility = View.GONE
        }
        itemView.find<ImageButton>(R.id.timeline_arc_button).apply {
            this.background.level = level
        }
        /*itemView.find<LinearLayout>(R.id.panel).apply {
            this.background.level = level
        }*/
        itemView.find<TimeLineView>(R.id.time_marker).apply {
            when (position) {
                0 -> {
                    setMarkPosition(TimeLineView.POINT_START)
                }
                3 -> {
                    setMarkPosition(TimeLineView.POINT_END)
                }
                else -> {
                    setMarkPosition(TimeLineView.POINT_MIDDLE)
                }
            }
            currentStatus = state
            setLastState(when {
                last == null -> {
                    TimeLineView.INACTIVE
                }
                last.isComplete -> {
                    TimeLineView.COMPLETE
                }
                else -> {
                    TimeLineView.INACTIVE
                }
            })
            setNextState(when (currentStatus) {
                TimeLineView.COMPLETE -> {
                    TimeLineView.COMPLETE
                }
                TimeLineView.INACTIVE -> {
                    TimeLineView.INACTIVE
                }
                TimeLineView.ACTIVE -> {
                    TimeLineView.INACTIVE
                }
                else -> {
                    TimeLineView.INACTIVE
                }
            })
            text = "" + (position + 1)
        }
        itemView.apply {
            backgroundDrawable?.level = level
            when (state) {
                TimeLineView.INACTIVE -> {
                    onClick { }
                }
                else -> {
                    onClick {
                        if (TokenManager.getInstance().hasLogin()) {
                            when (position) {
                                0 -> {
                                    FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_CERTIFICATION_STEP1, null)
                                    val intent = Intent(this@apply.context, InfoFillActivity::class.java)
                                    intent.putExtra(FieldParams.INFO_NO, position)
                                    intent.putExtra(FieldParams.NEED_OBTAIN_DATA, state == TimeLineView.COMPLETE)
                                    startActivity(this@apply.context, intent, null)
                                }
                                1 -> {
                                    FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_CERTIFICATION_STEP2, null)
                                    val intent = Intent(this@apply.context, PersonalInfoActivity::class.java)
                                    intent.putExtra(FieldParams.NEED_OBTAIN_DATA, state == TimeLineView.COMPLETE)
                                    startActivity(this@apply.context, intent, null)
                                }
                                2 -> {
                                    FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_CERTIFICATION_STEP3, null)
                                    val intent = Intent(this@apply.context, ContactInfoActivity::class.java)
                                    intent.putExtra(FieldParams.NEED_OBTAIN_DATA, state == TimeLineView.COMPLETE)
                                    startActivity(this@apply.context, intent, null)
                                }
                                3 -> {
                                    FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_CERTIFICATION_STEP4, null)
                                    val intent = Intent(this@apply.context, ProfessionalInfoActivity::class.java)
                                    intent.putExtra(FieldParams.NEED_OBTAIN_DATA, state == TimeLineView.COMPLETE)
                                    startActivity(this@apply.context, intent, null)
                                }
                                else -> {
                                }
                            }

                        } else {
                            toLogin()
                        }
                    }
                }
            }
        }
    }

    private fun toLogin() {
        XLeoToast.showMessage(R.string.please_login_first)
    }
}

interface CertifiFraView : FaceDetectorView {
    fun onSuccess(arrayList: ArrayList<CertBean>)
    fun onError(exception: Exception)
    fun resetCertItem()

}

class CertificatyFraPreImpl : CertifiFraProPresenter, FaceDetectorPreImpl() {
    override fun downloadState() {
        if (TokenManager.getInstance().hasLogin()) {
            showLoading("")
            mUserApi.progress(TokenManager.getInstance().token)
                    .zipWith(mUserApi.getLatestLoanApp(TokenManager.getInstance().token, "certifyFragment"), { i1, i2 ->
                        Pair(i1, i2)
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(object : Subscriber<Pair<ProgressBean, LatestLoanAppBean?>>() {
                        override fun onCompleted() {
                        }

                        override fun onError(p0: Throwable?) {
                            dismissLoading()
                            XLeoToast.showMessage(R.string.error_occured)
                            if (isAttached) {
                                (mView as CertifiFraView).onError(Exception(p0))
                            }
                        }

                        override fun onNext(p0: Pair<ProgressBean, LatestLoanAppBean?>?) {
                            dismissLoading()
                            if (p0?.first != null) {
                                if (isAttached) {
                                    val result = ArrayList<CertBean>()
                                    //修复用户在第一步，只上传了身份证照片，其他信息没有填写时，认为第一步已完成的bug
                                    //这里可以根据第二步的完成状态来判断第一步是否完成，因为第一步的部分数据是在第二步里面提交的
                                    //判断用户身份信息是否已经完成
//                                    result.add(CertBean(p0.first.isFilePart))
                                    result.add(CertBean(p0.first.isPersonalInfoPart))
                                    result.add(CertBean(p0.first.isPersonalInfoPart))
                                    result.add(CertBean(p0.first.isContactPart))
                                    result.add(CertBean(p0.first.isEmploymentPart))
                                    (mView as CertifiFraView).onSuccess(result)
                                    val second = p0.second
                                    var isEditable = false
                                    if (second == null) {
                                        isEditable = true
                                    } else {
                                        val status = second.status
                                        if (TextUtils.equals(status, FieldParams.LoanStatus.CLOSED)
                                                || TextUtils.equals(status, FieldParams.LoanStatus.REJECTED)
                                                || TextUtils.equals(status, FieldParams.LoanStatus.PAID_OFF)
                                                || TextUtils.equals(status, FieldParams.LoanStatus.WITHDRAWN)
                                                || TextUtils.equals(status, FieldParams.LoanStatus.NOLOANAPP)) {
                                            isEditable = true
                                        }
                                    }
                                    CacheDataManage.addData(FieldParamsInt.INFO_EDITABLE, isEditable)
                                }
                            } else {
                                onError(NullPointerException("result null"))
                            }

                        }

                    })
        } else {
            if (isAttached) {
                (mView as CertifiFraView).resetCertItem()
            }
        }
    }

}